#! /usr/bin/perl -w

# Author: Jari Enberg (kasa.lahtinen@gmail.com)

use strict;
use warnings;
use Irssi;
use HTML::Entities ();
use LWP::UserAgent;
use WWW::Shorten::TinyURL;

use vars qw($ua $ch_title $ch_tinyurl @settings);

$ua = LWP::UserAgent->new();
$ua->agent("URLBot 0.3");
$ua->timeout(5);

# add default channels

$ch_title = {
	"#channel_one"	=> 1,
};

$ch_tinyurl = {
	"#channel_two"	=> 1,
};

# Irssi settings

@settings = ("ub_channels_title", "ub_channels_tinyurl");

foreach(@settings){
  Irssi::settings_add_str("urlbot", $_, "");
}
Irssi::signal_add("message public", "handler_msg_pub");
Irssi::signal_add("setup changed", "regenerate_settings");

generate_settings();

sub regenerate_settings {
  foreach my $setting (@settings){
    my $channels = {};
    my $chstr = Irssi::settings_get_str($setting);
    $chstr =~ s/\s+//g;
    foreach(split(",", $chstr)){
	$channels->{$_} = 1;
    }
    if($setting =~ /title/){
	$ch_title = $channels;
    }
    elsif($setting =~ /tinyurl/){
	$ch_tinyurl = $channels;
    }
  }
  generate_settings();
}

sub generate_settings {
  foreach my $setting (@settings){
    my $chstr = "";
    if($setting =~ /title/){
	foreach my $channel (keys %{$ch_title}){
	  if($ch_title->{$channel} == 1){
	    $chstr = $chstr."$channel, ";
	  }
	}
    }
    elsif($setting =~ /tinyurl/){
	foreach my $channel (keys %{$ch_tinyurl}){
	  if($ch_tinyurl->{$channel} == 1){
	    $chstr = $chstr."$channel, ";
	  }
	}
    }
    $chstr = substr($chstr, 0, -2); # remove trailing ", "
    Irssi::settings_set_str($setting, $chstr);
  }
}

sub handler_msg_pub {
  my($server, $msg, $nick, $address, $target) = @_;
  return if (!$ch_title->{$target} && !$ch_tinyurl->{$target});
  $msg =~ /\b(https?:\/\/\S+)\b/i;
  my $url = $1;
  return if !$url;
  if($ch_title->{$target} == 1){
    my $url_escaped = $url;
    $url_escaped =~ s/%/%%/g;
    Irssi::print("URL detected: '$url_escaped'");
    my $req = HTTP::Request->new(GET => $url);
    $req->header(Accept => "text/html");
    my $res = $ua->request($req);
    if($res->is_error()){
	Irssi::print("request for '$url_escaped' failed: ".$res->message);
	return;
    }
    if($res->headers()->content_is_html){
	if($res->decoded_content =~ /<title>(.+)<\/title>/i){
	  my $title = $1;
	  $res->decoded_content =~ /<meta\s+property="og:title"\s+content="(.+?)".*\/>/i;
	  $title = $1 if $1;
	  $title = HTML::Entities::decode($title);
	  $server->command("/msg $target Title: $title");
	} else {
	  Irssi::print("title not found for '$url_escaped'");
	}
    }
  }
  elsif($ch_tinyurl->{$target} == 1){
    my $tinyurl = eval{ makeashorterlink($url) };
    $tinyurl = $@ if !$tinyurl;
    $server->command("/msg $target TinyURL: $tinyurl");
  }
}
